<?php

namespace app\common\library;

use app\common\model\Config;
use EasyWeChat\Factory;
use think\Env;

/**
 * 微信登录模型
 */
class Wechat
{

    protected $app;
    protected $config;

    public function __construct($platform)
    {
        $this->setConfig($platform);

        switch ($platform) {
            case 'wxOfficialAccount': //微信公众号
                $this->app = Factory::officialAccount($this->config);
                break;
            case 'wxMiniProgram': //微信小程序
                $this->app = Factory::miniProgram($this->config);
                break;
            case 'wxAppProgram': //微信app
                break;
        }
    }
    //微信app登录
    public static function wxAppLogin($code)
    {
        $appid = Env::get('wechat.app_id');
        $secret = Env::get('wechat.app_secret');
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
        $response = file_get_contents($url);
        $callback = json_decode($response, true);
        return $callback;
    }
    // 返回实例
    public function getApp()
    {
        return $this->app;
    }

    //小程序:获取openid&session_key
    public function code($code)
    {
        return $this->app->auth->session($code);
    }
    //获取手机号
    public function getPhone($code)
    {
        return $this->app->phone_number->getUserPhoneNumber($code);
    }
    //公众号授权登录
    public function oauth()
    {
        return $this->app->oauth;
    }
    //解密信息
    public function decryptData($session, $iv, $encryptData)
    {
        return $this->app->encryptor->decryptData($session, $iv, $encryptData);
    }

    public function unify($orderBody)
    {
        return $this->app->order->unify($orderBody);
    }
    //生成jsapi 
    public function bridgeConfig($prepayId, $url = '')
    {
        $jssdk = $this->app->jssdk;
        if ($url) {
            // 分享配置
            $jssdk->setUrl($url);
        }
        $config = $jssdk->bridgeConfig($prepayId, false);
        return $config;
    }
    //获取微信小程序码
    public function app_code($scene, $filename)
    {
        $data = [
            'page' => 'pages/index/goods',
            'width' => 600,
            'check_path' => false,
            'env_version' => 'trial' //正式版为"release"，体验版为"trial"，开发版为"develop"
        ];
        $response = $this->app->app_code->getUnlimit('scene=' . $scene, $data);
        $save_dir = 'uploads/shop';
        $filename = $filename . '.png';
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $file = $response->saveAs($save_dir, $filename);
            return '/' . $save_dir . '/' . $file;
        } else {
            return false;
        }
    }

    //获取accessToken
    public function getAccessToken()
    {
        $accessToken = $this->app->access_token;
        $token = $accessToken->getToken(); // token 数组 token['access_token'] 字符串
        return $token;
    }

    /**
     * 合并默认配置
     *
     * @param [type] $platform
     * @return void
     */
    private function setConfig($platform)
    {
        $debug = config('app_debug');
        $defaultConfig = [
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
            'log' => [
                'default' => $debug ? 'dev' : 'prod', // 默认使用的 channel，生产环境可以改为下面的 prod
                'channels' => [
                    // 测试环境
                    'dev' => [
                        'driver' => 'single',
                        'path'   => ROOT_PATH . 'public/logs/wechat_login.log',
                        'level'  => 'debug',
                    ],
                    // 生产环境
                    'prod' => [
                        'driver' => 'daily',
                        'path'   => ROOT_PATH . 'public/logs/wechat_login.log',
                        'level'  => 'info',
                    ],
                ],
            ],
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
            ],
        ];
        $minConfig = [
            'app_id' => Env::get('wechat.min_app_id'),
            'secret' => Env::get('wechat.min_secret'),
        ];
        $oauthConfig = [
            'app_id' => Env::get('wechat.oauth_app_id'),
            'secret' => Env::get('wechat.oauth_secret'),

        ];
        $appConfig = [
            'app_id' => Env::get('wechat.app_id'),
            'secret' => Env::get('wechat.app_secret'),
        ];
        // 根据框架 debug 合并 log 配置
        $this->config = $defaultConfig;
        // 根据框架 平台 合并 oauth 配置
        if ($platform === 'wxOfficialAccount') {
            $this->config = array_merge($this->config, $oauthConfig);
        }
        if ($platform === 'wxAppProgram') {
            $this->config = array_merge($this->config, $appConfig);
        }
        if ($platform === 'wxMiniProgram') {
            $this->config = array_merge($this->config, $minConfig);
        }
    }
}
